package com.ktjiaoyu.controller;


import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.SysUserService;
import com.ktjiaoyu.service.impl.SysUserServiceImpl;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController{
    private static final Logger LOGGER= LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/list")
    public String roleAll(Model model){
        Page<SysUser> page=null;
        try {
            List<SysRole> roleList=sysRoleService.findAll();
            model.addAttribute("list",roleList);
        }catch (Exception e){
            LOGGER.error("SysRoleController中的roleAll方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "role/list";
    }

    @RequestMapping("/view/{id}")
    public String roleById(@PathVariable("id") Long id,Model model){
        System.out.println(id);
        try {
            SysRole sysRole=sysRoleService.findById(id);
            model.addAttribute("sysRole",sysRole);
        }catch (Exception e){
            LOGGER.error("SysRoleController中的roleById方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "role/list";
    }

    @GetMapping(value = "/{id}/view",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map ajaxView(@PathVariable("id") Long id){
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        SysRole info=null;
        try {
            info=sysRoleService.findById(id);

            if(info!=null){
                resultMap.put("code",200);
                resultMap.put("data",info);
            }else{
                resultMap.put("code",500);
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的ajaxView方法执行错误。",e);
            resultMap.put("code",500);
        }
        return resultMap;
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        SysRole sysRole=null;
        try {
            sysRole=sysRoleService.findById(id);
            model.addAttribute("sysRole",sysRole);
        }catch (Exception e){
            LOGGER.error("SysRoleController中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @GetMapping("/save")
    public String toSave(Model model){
        try {
            model.addAttribute("sysRole",new SysRole());
        }catch (Exception e){
            LOGGER.error("SysRoleController中的toSave方法执行发生错误。",e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @ResponseBody
    @GetMapping("/codeExist")
    public String codeExist(@RequestParam("code") String code){
        LOGGER.info("检查用角色编码code={}的用户是否存在",code);
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        if (StringUtils.isEmpty(code)){
            resultMap.put("exist",0);
        }else {
            try {
                SysRole sysRole=sysRoleService.findByCode(code);
                if (null!=sysRole){
                    resultMap.put("exist",1);
                }else {
                    resultMap.put("exist",0);
            }
            }catch (Exception e){
                LOGGER.error("SysRoleController中的codeExist方法执行发生错误。",e);
                resultMap.put("error","出现异常，请联系管理员处理");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @PostMapping("/save")
    public String doSave(SysRole sysRole){
        try {
            int count=0;
            SysUser loginUser=session(Constants.SESSION_USER);
            if ((sysRole.getId()==null)){
                sysRole.setCreatedUserId(loginUser.getId());
                sysRole.setCreatedTime(new Date());
                count=sysRoleService.insertRole(sysRole);
            }else {
                sysRole.setUpdatedUserId(loginUser.getId());
                sysRole.setUpdatedTime(new Date());
                count=sysRoleService.updateRole(sysRole);
            }

            if (count>0){
                return redirect("/main/role/list");
            }
        }catch (Exception e){
            LOGGER.error("SysRoleController中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Map deleteRole(@PathVariable("id")Long id){
        HashMap<String,Object> resultMap=new HashMap<String,Object>();
        try {
            List<SysUser> sysUserList=sysUserService.selByRoleId(id);

            if (sysUserList.size()>0){
                resultMap.put("code","501");
                return resultMap;
            }

            int count=sysRoleService.deleteRole(id);
            if (count>0){
                resultMap.put("code","200");
                resultMap.put("msg","成功");
            }else {
                resultMap.put("code","500");
            }

        }catch (Exception e){
            LOGGER.error("SysRoleController中的deleteRole方法执行发生错误",e);
            throw new RuntimeException(e);
        }

        return resultMap;
    }
}
